package todlu.RssReader;

import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class AsyncImageLoader {
	private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
	private ExecutorService executorService = Executors.newFixedThreadPool(10);
	private final Handler handler=new Handler();
	
	public Drawable loadDrawable(final int id, final String imageUrl, final ImageCallback callback)
	{
		if(imageCache.containsKey(imageUrl))
		{
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if(softReference.get() != null)
			{
				return softReference.get();
			}
		}
		
		executorService.submit(new Runnable()
		{

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try
				{
					final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
					imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
					
					handler.post(new Runnable() 
					{

						@Override
						public void run() {
							// TODO Auto-generated method stub
							callback.imageLoaded(id, imageUrl, drawable);
						}
						
					});
				}
				catch(Exception ex)
				{
					throw new RuntimeException(ex);
				}
				
			}
			
		});
//		final Handler handler = new Handler()
//		{
//			@Override
//			public void handleMessage(Message msg)
//			{
//				callback.imageLoaded(id, imageUrl, (Drawable)msg.obj);
//			}
//		};
		
		new Thread()
		{
			public void run()
			{
				Drawable drawable = loadImageFromUrl(imageUrl);
				//imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				handler.sendMessage(handler.obtainMessage(1, drawable));
			}
		}.start();
		
		return null;
	}
	
	protected Drawable loadImageFromUrl(String imageUrl) {
        try {
            return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
        } catch (Exception e) {
            //throw new RuntimeException(e);
        	Log.d("RssReader-Exp", e.getMessage());
        	return null;
        }
    }
	
	public interface ImageCallback
	{
		public void imageLoaded(int id, String imageUrl, Drawable imageDrawable);
	}
}
